package com.samsung.spen.sshare.main.sms;

import java.util.ArrayList;
import java.util.Date;

import com.samsung.spen.sshare.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract.PhoneLookup;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.samsung.spen.sshare.main.MainActivity;
import com.samsung.spen.sshare.main.data.RequestSMS;
import com.samsung.spen.sshare.main.data.SshareDataService;

public class RequestSMSListFragment extends Fragment implements OnItemClickListener{
	private int mNum;
	private ListView mListView = null;
	private MainActivity bindedActivity = null;
	private View view = null;
	private ArrayList<RequestSMS> mRequests = new ArrayList<RequestSMS>();
	private ArrayList<View> actualViews = new ArrayList<View>();
	private Menu menu;
	private SMSComeReceiver receiver = new SMSComeReceiver();
	
	private SshareDataService mSshareDataService;
	private ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mSshareDataService = null;
			Toast.makeText(bindedActivity, "service disconnected",
					Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mSshareDataService = ((SshareDataService.SshareDataServiceBinder) service)
					.getService();
			// use service here
			Toast.makeText(bindedActivity, "service connected",
					Toast.LENGTH_SHORT).show();
			Log.v(this.getClass().toString(), "service connected");
//			for(int i = 0; i<50; i++){
//				mSshareDataService.insertSMS("0987654321", 987654321, "bonjour", "192.168.1.101");
//			}
			refreshListView();
		}
	};

	public RequestSMSListFragment newInstance(int num) {
		RequestSMSListFragment f = new RequestSMSListFragment();

		Bundle args = new Bundle();
		args.putInt("num", num);
		f.setArguments(args);

		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mNum = getArguments() != null ? getArguments().getInt("num") : 1;
		this.bindedActivity = (MainActivity) this.getActivity();
		setHasOptionsMenu(true);


		bindedActivity.bindService(new Intent(bindedActivity, SshareDataService.class),
				mServiceConnection, Context.BIND_AUTO_CREATE);
		
		Log.v(this.getClass().toString(), "oncreate requestsmsListFragment");
	}
	
	@Override
	public void onResume() {
		super.onResume();
		IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
		filter.setPriority(Integer.MAX_VALUE);
		bindedActivity.registerReceiver(receiver, filter);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.main_activity_sms_requests, container,
				false);
		this.view = v;
		return v;
	}
	
	@Override
	public void onActivityCreated(Bundle bundle) {
		super.onActivityCreated(bundle);
		mListView = (ListView) view.findViewById(R.id.lv_requests);
		RequestDataAdapter adapter = new RequestDataAdapter(bindedActivity);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		
		Log.v(this.getClass().toString(), "onactivitycreate requestsmsListFragment");
	}
	
	@Override
	public void onStop() {
		super.onDestroy();
		bindedActivity.unregisterReceiver(receiver);
		super.onStop();
	}
	
	@Override
	public void onDestroy() {
		if(mServiceConnection!=null){
			bindedActivity.unbindService(mServiceConnection);
		}
		super.onDestroy();
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.main_fragment_requestsms, menu);
		this.menu = menu;
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_select_all:
			for (RequestSMS requestSMS : mRequests) {
				requestSMS.setChecked(true);
			}
			for (View view : actualViews) {
				((CheckBox)view.findViewById(R.id.cb_request)).setChecked(true);
			}
			item.setVisible(false);
			this.menu.getItem(2).setVisible(true);
			break;
		case R.id.menu_deselect_all:
			for (RequestSMS requestSMS : mRequests) {
				requestSMS.setChecked(false);
			}
			for (View view : actualViews) {
				((CheckBox)view.findViewById(R.id.cb_request)).setChecked(false);
			}
			item.setVisible(false);
			this.menu.getItem(1).setVisible(true);
			break;
		case R.id.menu_delete_selected:
			for (RequestSMS requestSMS : mRequests) {
				if(requestSMS.isChecked()){
					mSshareDataService.deleteRequestSMS(requestSMS.getId());
				}
			}
			refreshListView();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void refreshListView(){
		mRequests = mSshareDataService.getRequestSMSList();
		RequestDataAdapter adapter = new RequestDataAdapter(bindedActivity);
		mListView.setAdapter(adapter);
	}
	
	class RequestDataAdapter extends ArrayAdapter<RequestSMS>{
		public RequestDataAdapter(Context ctx){
			super(ctx, R.layout.main_listview_request_item, mRequests);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			DataHolder holder;
			if(row == null){
				LayoutInflater inflater = bindedActivity.getLayoutInflater();
				row = inflater.inflate(R.layout.main_listview_request_item, parent, false);
				holder = new DataHolder(row);
				row.setTag(holder);
				actualViews.add(row);
			} else {
				holder = (DataHolder) row.getTag();
			}
			holder.setData(mRequests.get(position), position);
			return row;
		}
	}
	
	class DataHolder {
		ImageView ivConnectionState;
		TextView tvContact, tvPhone, tvDateTime;
		CheckBox cb;
		int position;
		
		public DataHolder(View view){
			ivConnectionState = (ImageView) view.findViewById(R.id.iv_connection_state);
			tvContact = (TextView) view.findViewById(R.id.tv_contact);
			tvPhone = (TextView) view.findViewById(R.id.tv_phone);
			tvDateTime = (TextView) view.findViewById(R.id.tv_date_time);
			cb = (CheckBox) view.findViewById(R.id.cb_request);
			cb.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					mRequests.get(position).setChecked(cb.isChecked());
					//Log.v(RequestSMSListFragment.class.toString(), position+":"+ cb.isChecked());
				}
			});
		}
		
		public void setData(RequestSMS request, int pos){
			this.position = pos;
			String name = "No contact";
			name = bindedActivity.getNameFromPhone(request.getPhoneNumber());
			if(request.getStatus() == Constants.SMS_UNREAD){
				tvContact.setTypeface(null, Typeface.BOLD_ITALIC);
			} else if(request.getStatus() == Constants.SMS_READ ){
				tvContact.setTypeface(null, Typeface.NORMAL);
			}
			tvContact.setText(name); 
			tvPhone.setText(request.getPhoneNumber());
			tvDateTime.setText((new Date(request.getDateTime())).toString());
			cb.setChecked(request.isChecked());
			//Log.v(RequestSMSListFragment.class.toString(), request.isChecked()+"");
		}
	}
	
	class SMSComeReceiver extends BroadcastReceiver implements Constants {
		private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(SMS_RECEIVED)) {
				Bundle bundle = intent.getExtras();
				Log.d(this.getClass().toString(), "SMS received");
				Toast.makeText(context, "sms received", Toast.LENGTH_SHORT).show();
				Object[] pdus = (Object[]) bundle.get("pdus");
				SmsMessage[] messages = new SmsMessage[pdus.length];
				for (int i = 0; i < pdus.length; i++) {
					messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				}

				String body = "";
				String phoneNum = "";
				long time = 0;
				String ip;
				String content;

				SmsMessage sms = messages[0];
				phoneNum = messages[0].getDisplayOriginatingAddress();
				time = messages[0].getTimestampMillis();
				try {
					if (messages.length == 1 || sms.isReplace()) {
						body = sms.getDisplayMessageBody();
					} else {
						StringBuilder bodyText = new StringBuilder();
						for (int i = 0; i < messages.length; i++) {
							bodyText.append(messages[i].getMessageBody());
						}
						body = bodyText.toString();
					}
					if(body.contains(TOKEN_SEPARATED))
					{
						String[] tokens = body.split(TOKEN_SEPARATED);
						if(tokens[0].equals(INDENTIFICATION_STRING)){
							this.abortBroadcast();
							//Handle sms
							ip = tokens[1];
							content = tokens[2];
							mSshareDataService.insertSMS(phoneNum, time, content, ip);
							
							//fire notification 
							NotificationCompat.Builder builder = new Builder(bindedActivity);
							builder.setSmallIcon(R.drawable.ic_launcher);
							builder.setContentTitle("Request From : " + phoneNum);
							builder.setContentText(content);
							NotificationManager mNotificationManager = (NotificationManager) bindedActivity.getSystemService(Context.NOTIFICATION_SERVICE);
							Notification notification = builder.build();
							
							Intent intentNtf = new Intent(bindedActivity, MainActivity.class);
							intentNtf.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							PendingIntent pi = PendingIntent.getActivity(bindedActivity, 0, intentNtf, 0);
							notification.contentIntent = pi;
							notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;

							mNotificationManager.notify((int)System.currentTimeMillis(), notification);
							
							
							//refresh listview
							refreshListView();
							Log.v(RequestSMSListFragment.class.toString(), "receive SMS in SMSListFragment");
						}
					}

					Log.d(this.getClass().toString(), body);
				} catch (Exception e) {

				}
			}
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if(parent.getId() == R.id.lv_requests){
			//Toast.makeText(bindedActivity, "click", Toast.LENGTH_SHORT).show();
			AlertDialog.Builder builder = new AlertDialog.Builder(bindedActivity);
			RequestSMS sms = mRequests.get(position);
			builder.setTitle(sms.getPhoneNumber());
			builder.setMessage(sms.getContent());
			builder.setCancelable(true);
			builder.setPositiveButton("Send Files", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
			});
			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
			});
			builder.create().show();
			mSshareDataService.updateSMSStatus(Constants.SMS_READ, sms.getId());
			sms.setStatus(Constants.SMS_READ);
			refreshListView();
		}
		
	}
}
